package com.packenius.library.xspdf.hacks;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.packenius.library.xspdf.XS;
import com.packenius.library.xspdf.XSContentListenerAdapter;
import com.packenius.library.xspdf.XSPDF;
import com.packenius.library.xspdf.XSPageSize;

/**
 * Form text column via image mask.
 */
public class Example_Hack002 implements XS {
  /**
   * @param args Unused.
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    XSPDF xsPDF = new XSPDF();
    final String doNotFillColumnName = "do not fill!";
    xsPDF.setFont(HELVETICA, xsPDF.getFontSize() / 2.0);
    double pageSize = 500.0;
    xsPDF.use(new XSPageSize(pageSize, pageSize), NO_MARGIN, NO_INDENTATION);
    BufferedImage mask = ImageIO.read(new File("img/bw-heart.jpg"));
    int maskWidth = mask.getWidth();
    int maskHeight = mask.getHeight();
    double dx = pageSize / maskWidth;
    double dy = pageSize / maskHeight;
    for (int y = 0; y < maskHeight; y++) {
      int kx = -1;
      for (int x = 0; x < maskWidth; x++) {
        int rgb = mask.getRGB(x, y);
        if ((rgb & 255) > 16 && (rgb >> 8 & 255) > 16 && (rgb >> 16 & 255) > 16) { // "Not black"?
          if (kx == -1) {
            kx = x;
          }
        } else {
          if (kx >= 0) {
            xsPDF.addColumn(kx * dx, y * dy, (x - kx) * dx, (y + 1) * dy, doNotFillColumnName, 0);
            kx = -1;
          }
        }
      }
      if (kx >= 0) {
        xsPDF.addColumn(kx * dx, y * dy, (maskWidth - kx) * dx, (y + 1) * dy, doNotFillColumnName, 0);
      }
    }
    xsPDF.addColumns(1, null);
    xsPDF.addContentListener(new XSContentListenerAdapter() {
      @Override
      public void newColumn(XSPDF xsPDF, int pageID, String columnName) {
        if (doNotFillColumnName.equals(columnName)) {
          xsPDF.nextColumn();
        }
      }
    });
    for (int i = 0; i < 1425; i++) {
      xsPDF.print("" + i);
    }
    xsPDF.createPdf("pdf/Hack 002.pdf");
  }
}
